<template>
  <div class="reader">
    <div
      class="book"
      ref="wrapper"
      :style="{
        color: pattern[patternActive].color,
        background: pattern[patternActive].background,
      }"
    >
      <!-- 书籍内容 - 上下滑动阅读  v-if="pagingPattern===0"-->
      <div
        class="books-con"
        v-infinite-scroll="loadMore"
        infinite-scroll-disabled="loading"
        infinite-scroll-distance="0"
        infinite-scroll-immediate-check="false"
      >
        <div class="book-head" :class="{ 'head-height': option }">
          <mt-popup
            class="book-head-Popup"
            v-model="option"
            position="top"
            :modal="false"
          >
            <mt-header :title="currentChapter.title">
              <router-link to slot="left">
                <mt-button @click="$router.back(-1)" icon="back"></mt-button>
              </router-link>
            </mt-header>
          </mt-popup>
        </div>
        <div @click="setRead" class="book-content" ref="content">
          <h1 class="book-title" :style="{ fontSize: fontSize * 1.2 + 'px' }">
            {{ currentChapter.title }}
          </h1>
          <div
            class="book-inner"
            v-html="bookContent.content"
            :style="{ fontSize: fontSize + 'px' }"
          ></div>
        </div>
        <div class="loadMore" style="text-align: center" v-show="moreLoading">
          <mt-spinner type="triple-bounce" color="#409eff"></mt-spinner>
        </div>
      </div>
      <!-- 引导页 -->
      <div class="bootPage" @click="bootPage = false" v-if="bootPage">
        <div class="b-item bootPage-left">
          <div class="center">
            <i class="fa fa-angle-left"></i><span>点击左侧翻页</span>
          </div>
        </div>
        <div class="b-item bootPage-center">
          <div class="center">呼出菜单</div>
        </div>
        <div class="b-item bootPage-right">
          <div class="center">
            <span>点击右侧翻页</span><i class="fa fa-angle-right"></i>
          </div>
        </div>
      </div>
      <!-- 书籍内容 - 左右翻页阅读 -->
      <!-- <div class="read-content" v-if="pagingPattern===1">
          <p class="book-title" style="padding: 10px">{{bookContent.title}}</p>
          <div class="read-article">
            <section class="read-section" :style="styleObject">
              <div class="read-section-inner" :style="{columns:clWidth-20+'px',columnGap:10+'px'}"
                  ref="bookInner" id="bookInner">
                <h1 class="book-title" :style="{fontSize:fontSize*1.2+'px'}">{{bookContent.title}}</h1>
                <div class="book-inner" :style="{fontSize:fontSize+'px'}"
                    v-html="bookContent.content"></div>
              </div>
            </section>
          </div>
          <p class="article-page">{{currentPaging + '/' + resultPaging}}</p>
        </div> -->
      <div class="foot-toggle-chapter">
        <button
          :class="{ 'toggle-astrict': currentChapterSort <= 1 }"
          @click.stop="preOrNextChapter('pre')"
        >
          Previous
        </button>
        <button @click.stop="preOrNextChapter('next')">Next</button>
      </div>
    </div>
    <!-- 展示工具 -->
    <mt-popup
      class="book-foot"
      v-model="option"
      position="bottom"
      :modal="false"
    >
      <div
        v-if="isBookself === 0"
        class="add-bookself"
        @click="addBookToBookCase()"
      >
        <svg-icon icon-class="add-bookself"></svg-icon>
        <span>Add to Bookself</span>
      </div>
      <div class="page-read-option">
        <ul class="set-fontSize">
          <li
            @click.stop="fontSet('reduce', $event)"
            :class="{ 'fontSize-astrict': fontSize <= 14 }"
            class="fontSize-reduce"
          >
            A-
          </li>
          <li class="fontSize-num" v-text="fontSize"></li>
          <li
            @click.stop="fontSet('add', $event)"
            :class="{ 'fontSize-astrict': fontSize >= 22 }"
            class="fontSize-add"
          >
            A+
          </li>
        </ul>
        <ul class="set-colour">
          <li
            v-for="(val, idx) of pattern"
            @click.stop="setPattern(val, idx)"
            :key="val.item"
            :class="{ active: idx == patternActive }"
            :style="{ backgroundColor: val.background }"
          ></li>
        </ul>
        <ul class="set-list">
          <li @click="isChapterList = true">
            <svg-icon icon-class="menuChapter"></svg-icon>
          </li>
          <li @click="switchTheme">
            <svg-icon
              v-if="patternActive === 3"
              icon-class="darkMode"
            ></svg-icon>
            <svg-icon v-else icon-class="lightMode"></svg-icon>
          </li>
          <li @click="preOrNextChapter('pre')">
            <svg-icon icon-class="preChapter"></svg-icon>
          </li>
          <li @click="preOrNextChapter('next')">
            <svg-icon icon-class="nextChapter"></svg-icon>
          </li>
        </ul>
      </div>
    </mt-popup>
    <!-- 章节列表 -->
    <div class="chapter-list">
      <mt-popup v-model="isChapterList" position="left">
        <div class="chapter-head">
          <div class="chapter-head-box">
            <span
              class="episodes"
              v-text="chapterList.length + ' Episodes'"
            ></span>
            <span class="sort" @click="chapterListSort(sort)">
              <svg-icon
                :icon-class="sort ? 'order-icon' : 'reverse-icon'"
              ></svg-icon>
            </span>
          </div>
        </div>
        <ul class="list">
          <li
            v-for="item of chapterList"
            @click="toggleChapter(item)"
            :class="{
              active: item.contentId == currentChapter.contentId,
            }"
            :key="item.contentId"
            :chapterName-content="item.title"
          >
            <span class="lock-box" v-show="item.isBuy !== 2">
              <svg-icon
                :icon-class="
                  item.isBuy || currentUnlockIds.indexOf(item.contentId) != -1
                    ? 'unlock-icon'
                    : 'lock-icon'
                "
              ></svg-icon>
            </span>
          </li>
        </ul>
      </mt-popup>
    </div>
    <!-- 添加书架弹窗 -->
    <div class="add-bookself-box">
      <mt-popup v-model="isBookselfPopup">
        <div class="bookself-popup">
          <img class="bookself-bg" src="@/assets/images/bookself-bg.png" />
          <p class="content">Add to Bookself</p>
          <div class="foot-btn">
            <mt-button @click="addBookself('cancel')" class="cancel"
              >Cancel</mt-button
            >
            <mt-button @click="addBookself('confirm')" class="confirm"
              >OK</mt-button
            >
          </div>
        </div>
      </mt-popup>
    </div>
    <!-- 解锁章节弹窗 -->
    <div class="unlock-chapter">
      <mt-popup
        v-model="unlockChapterPopup"
        :modal="false"
        closeOnClickModal
        position="bottom"
      >
        <div class="unlock-chapter-popup">
          <h3 class="title">THANK YOU!</h3>
          <div class="unlock-btn-box">
            <mt-button class="free-btn" @click="unlockChapter('premium')"
              ><svg-icon icon-class="free-btn-icon" slot="icon"></svg-icon>Free
              Reading For Premium
            </mt-button>
            <mt-button
              v-if="bookContent.coinBalance < bookContent.price"
              @click="unlockChapter('myAccount')"
              class="purchase-btn"
              v-text="'Purchase coins read'"
            ></mt-button>
            <mt-button
              v-else
              class="unlock-btn"
              @click="unlockChapter('unlock')"
              v-text="`${bookContent.price} coins to read this episode`"
            ></mt-button>
          </div>
          <div class="auto-subscribe">
            <input
              v-model="autoSubscribe"
              type="checkbox"
              id="auto-subscribe"
              name="auto"
              @change="setUserLocalStorage"
            />
            <label for="auto-subscribe"
              >Auto-subscribe to the next chapter</label
            >
          </div>
          <div
            class="account-balance"
            :class="{ subscribe: bookContent.coinBalance < bookContent.price }"
            :subscribe-content="`${bookContent.price} coins to subscribe this chapter`"
          >
            <p
              v-if="unlockChapterPopup"
              v-text="`${utils.tranNumber(bookContent.coinBalance, 1)} Coins`"
            ></p>
          </div>
          <div class="foot-toggle-chapter foot-btn">
            <button
              :class="{ 'toggle-astrict': currentChapterSort <= 1 }"
              @click.stop="preOrNextChapter('pre')"
            >
              Previous
            </button>
            <button @click.stop="preOrNextChapter('next')">Next</button>
          </div>
        </div>
      </mt-popup>
    </div>
    <div class="products-pay">
      <mt-popup v-model="payPopup" position="bottom">
        <div class="pay-popup">
          <div class="header">
            <span
              >Insufficient coins, please recharge and continue reading.</span
            >
            <router-link class="view-all" to="/myAccount"
              >View All ></router-link
            >
          </div>
          <div class="card-list-box">
            <ul v-for="(arr, idx) of cardList" :key="idx" class="card-list">
              <li
                v-for="item of arr"
                :key="item.rechargeId || item.vipId"
                :class="{
                  dot: item.characterCorner ? true : false,
                  active: item.rechargeId
                    ? item.rechargeId == currentCard.rechargeId
                    : item.vipId == currentCard.vipId,
                }"
                :li-content="item.characterCorner"
                @click="currentCard = item"
              >
                <div class="info">
                  <h3
                    :title-content="item.conversionCoin ? 'COINS' : ''"
                    v-text="item.conversionCoin || item.vipNameEns"
                  ></h3>
                  <p
                    class="desc ellipsis"
                    :add-content="item.giveCoin ? '+' : ''"
                    :desc-content="item.giveCoin ? 'COINS' : ''"
                    v-text="item.giveCoin || item.text"
                  ></p>
                </div>
                <div
                  class="price"
                  v-text="'$ ' + (item.rechargeSum || item.price)"
                ></div>
              </li>
            </ul>
          </div>
          <pay-list
            :payListStyle="'reader-pay-list'"
            :currentCard="currentCard"
            @recharge="recharge"
          ></pay-list>
        </div>
      </mt-popup>
    </div>
    <!-- <div class="changeSource">

      </div> -->
  </div>
</template>

<script>
import axios from "api/index";
import api from "api/global_variable";
import { mapMutations, mapGetters } from "vuex";
import PayList from "components/common/PayList/Index";
import { Toast } from "mint-ui";
import CryptoJS from "crypto-js";
export default {
  data() {
    return {
      bookId: this.$route.params.id, //书籍ID
      chapterList: [], //书籍目录
      isChapterList: false, //打开章节列表
      sort: true, //章节列表排序
      currentChapterSort: 1, //当前章节序号
      isBookself: 0, // 工具栏是否展示加入书架按钮
      isBookselfPopup: false, //加入书架弹窗
      unlockChapterPopup: false, //解锁章节弹窗
      payPopup: false, //充值浮窗
      cardList: {}, //充值套餐列表
      currentCard: {}, //当前选中的套餐
      autoSubscribe: false, //自动购买章节
      currentUnlockIds: [], //当前解锁的章节ID集合
      // 书籍内容
      bookContent: {}, //当前内容详情
      bookCurrentPage: 0,
      bookSourceLinks: [],
      loading: false,
      option: true, //是否显示工具
      moreLoading: false,
      // Colour 更换背景
      pattern: [
        {
          item: "默认",
          color: "#5c5d58",
          background: "#F7F7F7",
        },
        {
          item: "护眼",
          color: "#5c5d58",
          background: "#DFFFE6",
        },
        {
          item: "浅色",
          color: "#5c5d58",
          background: "#EAFDFF",
        },
        {
          item: "夜间",
          color: "#666",
          background: "#000",
        },
      ],
      patternActive: 0, //当前Colour下标
      // offsetX: 0, //阅读位置
      // styleObject: '',
      // currentPaging: 1,
      // resultPaging: 1,
      fontSize: 16,
      // pagingPattern: 0, //阅读模式 滑动-翻页
      bootPage: false, //是否显示引导页
      // clWidth:
      //   document.documentElement.clientWidth || document.body.clientWidth,
      scrollTop: 0,
      bookReadAnalysis: {}, //书籍阅读数据日志参数
      saveTime: Date.now(), //记录时间戳
    };
  },
  components: {
    PayList,
  },
  computed: {
    ...mapGetters(["userInfo"]),
    // nextChapterText() {
    //   if (this.currentChapterSort >= this.chapterList.length) {
    //     return "More Chapter";
    //   } else {
    //     return "Next";
    //   }
    // },
    // 当前章节信息
    currentChapter() {
      if (this.chapterList.length > 0) {
        let item = this.chapterList.find((ele) => {
          return ele.sort == this.currentChapterSort;
        });
        if (item) {
          if (item.isBuy === 0 && this.autoSubscribe == true) {
            //开启自动订阅下一章
            this.buyChapter(item.contentId);
          } else {
            this.getChapterDetails(item);
          }
        }
        return item;
      } else {
        return {};
      }
    },
  },
  watch: {
    // 监听书架弹窗 判断是否添加历史记录  阻止退出事件
    // isBookselfPopup(newVal) {
    //   if (newVal === false) {
    //     if (this.isBookself === 0) {
    //       window.history.pushState(null, null, document.URL);
    //     }
    //   }
    // },
  },
  created() {
    // this.getNewUser();
    this.getUserLocalStorage();
    this.localRead("get");
    this.getBookInfo();
  },
  mounted() {
    this.getChapterList();
    this.option = true;
    this.doIt();
    // 关闭或刷新浏览器调用事件
    window.addEventListener("beforeunload", (e) => {
      this.beforeunloadHandler(e);
    });
  },
  destroyed() {
    window.removeEventListener("popstate", this.goBack, false);
    window.removeEventListener("beforeunload", (e) =>
      this.beforeunloadHandler(e)
    );
    this.localRead("set");
    this.sendLog("book_read_analysis");
  },
  // 对keep-alive缓存页面进行清除
  // deactivated() {
  //   window.removeEventListener("popstate", this.goBack, false);
  //   window.removeEventListener("beforeunload", (e) =>
  //     this.beforeunloadHandler(e)
  //   );
  //   this.localRead("set");
  //   this.sendLog("book_read_analysis");
  // },
  methods: {
    ...mapMutations({
      setShowPopup: "SET_SHOW_POPUP",
      setCurrentPopup: "SET_CURRENT_POPUP",
    }),
    //浏览器关闭/刷新事件
    beforeunloadHandler() {
      this.localRead("set");
      this.sendLog("book_read_analysis");
    },
    //子组件 充值完成调用
    recharge() {
      this.payPopup = false;
      this.getChapterDetails(this.currentChapter);
    },
    // 存取阅读记录
    localRead(flag) {
      //退出阅读器时调用 存储阅读记录
      if (flag === "set") {
        // if (this.currentChapterSort > 1) {
        let map;
        if (this.utils.seekStore("readingLog")) {
          map = new Map(this.utils.getStore("readingLog"));
          map.set(this.bookId, this.currentChapterSort);
          if (map.size > 50) {
            map.delete(map.keys().next().value);
          }
        } else {
          map = new Map();
          map.set(this.bookId, this.currentChapterSort);
        }
        this.utils.setStore("readingLog", Array.from(map.entries()));
        // }
      } else if (flag === "get") {
        // 进入阅读器调用 获取本地存储记录
        if (this.userInfo) {
          this.getBookRead();
        } else {
          if (this.utils.seekStore("readingLog")) {
            let map = new Map(this.utils.getStore("readingLog"));
            if (map.has(this.bookId)) {
              this.currentChapterSort = map.get(this.bookId);
              // 是否第一次阅读：1.是，0.否
              this.bookReadAnalysis.isFirstRead = 0;
            } else {
              this.bookReadAnalysis.isFirstRead = 1;
            }
          }
        }
      }
    },
    // 获取书籍详情
    async getBookInfo() {
      try {
        const baseUrl = api.apiUrl;
        let url = baseUrl + `/book/info/${this.bookId}`;
        let res = await axios.get(url);
        if (res.code === 1) {
          let opts = {
            logType: 1, //日志类型：1.电子书，2.AI听书，3.有声小说
            isTitlePage: 0, //是否扉页：1.是，0.否
            bookId: this.bookId, //书籍id
            bookName: res.source.bookTitle, //书籍名称
            authorName: res.source.authorName, //作者名称
            cpId: res.source.channelId, //cp方id
            preference: res.source.site, //书籍男女：1.男，2.女
            categoryIdOne: res.source.categoryId1, //书籍分类一级id
            categoryIdTwo: res.source.categoryId2, //书籍分类二级id
            isFreeBook: res.source.isFree, //是否免费书籍：1.是，0.否
          };
          Object.assign(this.bookReadAnalysis, opts);
        }
      } catch (e) {
        console.log(e);
      }
    },
    async sendLog(txt) {
      if (txt === "book_read_analysis") {
        let now = Date.now();
        let time = now - this.saveTime;
        if (
          time > 1000 &&
          (this.currentChapter.isBuy != 0 ||
            this.currentUnlockIds.indexOf(this.currentChapter.contentId) != -1)
        ) {
          let opts = {
            chapterId: this.currentChapter.contentId, //章节id
            chapterName: this.currentChapter.title, //章节名称
            chapterSort: this.currentChapter.sort, //章节序号
            isFreeChapter: this.currentChapter.isBuy == 2 ? 1 : 0, //是否免费章节：1.是，0.否
            isBuyChapter:
              this.currentChapter.isBuy == 1
                ? 1
                : this.currentUnlockIds.indexOf(
                    this.currentChapter.contentId
                  ) != -1
                ? 1
                : 0, //是否购买章节：1.是，0.否
            readTime: time > 1200000 ? 1200000 : time, //章节阅读时长（毫秒） 超过20分钟上报20
            deviceIdChapterId: localStorage.getItem("local_user")
              ? JSON.parse(localStorage.getItem("local_user")).userId +
                this.currentChapter.contentId
              : "",
          };
          Object.assign(this.bookReadAnalysis, opts);
          // this.bookReadAnalysis. = time;
          // this.saveTime = now;

          // this.bookReadAnalysis.readTime = now - this.saveTime;
          await this.$api.logger.book_read_analysis(this.bookReadAnalysis);
        }
        this.saveTime = now;

        // this.saveTime = Date.now();
      }
    },
    //获取是否为新用户，新用户的则需要引导页
    // getNewUser() {
    //   if (window.localStorage.getItem("bootPage") != null) {
    //     this.bootPage = this.utils.getStore("bootPage");
    //   } else {
    //     this.bootPage = true;
    //     window.localStorage.setItem("bootPage", false);
    //   }
    // },
    //点击弹出工具栏
    setRead() {
      this.option = !this.option;
    },
    // 获取用户设置
    getUserLocalStorage() {
      if (window.localStorage.getItem("readPattern") != null) {
        let localShelf = JSON.parse(window.localStorage.getItem("readPattern"));
        this.fontSize = localShelf.fontSize;
        this.patternActive = localShelf.patternActive;
        this.autoSubscribe = localShelf.autoSubscribe;
      }
    },
    //将用户设置进行缓存
    setUserLocalStorage() {
      // let localShelf = JSON.parse(window.localStorage.getItem('readPattern')) ? JSON.parse(window.localStorage.getItem('readPattern')) : {};
      let localShelf = {
        fontSize: this.fontSize, //字体大小
        patternActive: this.patternActive, //Colour下标
        autoSubscribe: this.autoSubscribe, //自动订阅下一章
        // pagingPattern: this.pagingPattern, //阅读模式 滑动-翻页
      };
      window.localStorage.setItem("readPattern", JSON.stringify(localShelf));
    },
    // 获取书籍目录
    async getChapterList() {
      try {
        let params = {
          bookId: this.bookId,
          sortType: 0,
        };
        let res = await this.$api.reader.getChapterList(params);
        if (res.code === 1) {
          this.chapterList = res.source.sort(this.utils.compareSort("sort"));
          // this.currentChapterSort = this.chapterList[0].contentId;
          // this.getBookRead();
        }
      } catch (e) {
        console.log(e);
      }
    },
    // 获取章节详情
    async getChapterDetails(item) {
      try {
        let params = {
          bookId: this.bookId,
          chapterId: item.contentId,
        };
        // this.unlockChapterPopup = !item.isBuy;
        let res = await this.$api.reader.getChapterDetails(params);
        if (res.code === 1) {
          let obj = this.decryptAES(res.source);
          obj = obj
            .replace(/\\n/g, "\\n")
            .replace(/\\'/g, "\\'")
            .replace(/\\"/g, '\\"')
            .replace(/\\&/g, "\\&")
            .replace(/\\r/g, "\\r")
            .replace(/\\t/g, "\\t")
            .replace(/\\b/g, "\\b")
            .replace(/\\f/g, "\\f")
            .replace(/\//g, "/");
          //移除不可打印的或者其他无效的json字符
          obj = obj.replace(/[\u0000-\u0019]+/g, "");
          let json;
          try {
            json = JSON.parse(obj);
          } catch (e) {
            json = eval("(" + obj + ")");
          }
          // console.log(json);
          //解锁章节弹窗
          this.unlockChapterPopup = !json.isBuy;
          this.bookContent = json;
          this.backTop();
        }
      } catch (e) {
        console.log(e);
      }
    },
    //章节排序
    chapterListSort(sort) {
      if (sort === true) {
        this.sort = false;
        this.chapterList = this.chapterList.sort(
          this.utils.compareReverse("sort")
        );
      } else {
        this.sort = true;
        this.chapterList = this.chapterList.sort(
          this.utils.compareSort("sort")
        );
      }
    },
    // 购买章节
    async buyChapter(chapterId) {
      try {
        let params = {
          bookId: this.bookId,
          chapterId,
        };
        let res = await this.$api.reader.buyChapter(params);
        if (res.code === 1) {
          this.unlockChapterPopup = false;
          this.bookContent.content = this.decryptAES(res.source);
          this.backTop();
          this.currentUnlockIds.push(chapterId);
          // this.getReadSave(chapterId);
          let opts = {
            bookId: this.bookId, //书籍id
            bookName: this.bookReadAnalysis.bookName,
            chapterId: this.currentChapter.contentId,
            chapterName: this.currentChapter.title,
            chapterSort: this.currentChapter.sort,
          };
          await this.$api.logger.book_subscribe_analysis(opts);
          this.saveTime = Date.now();
        } else {
          this.getChapterDetails(this.currentChapter);
          this.unlockChapterPopup = true;
          Toast(res.message);
        }
      } catch (e) {
        console.log(e);
      }
    },
    // 查询用户的书籍阅读记录(已登录情况下)
    async getBookRead() {
      let params = {
        bookId: this.bookId, //书籍id
      };
      let res = await this.$api.reader.getBookRead(params);
      if (res.code === 1 && res.source) {
        this.isBookself = res.source.isCollect;
        if (res.source.cOrder) {
          this.bookReadAnalysis.isFirstRead = 0; // 是否第一次阅读：1.是，0.否
          //如果后端返回阅读记录 比较本地-服务器阅读记录
          if (this.utils.seekStore("readingLog")) {
            let map = new Map(this.utils.getStore("readingLog"));
            this.currentChapterSort = map.has(this.bookId)
              ? Math.max(map.get(this.bookId), res.source.cOrder)
              : res.source.cOrder;
          } else {
            this.currentChapterSort = res.source.cOrder;
          }
        } else {
          this.bookReadAnalysis.isFirstRead = 1;
          // 未返回阅读记录字段 取本地阅读记录
          if (this.utils.seekStore("readingLog")) {
            let map = new Map(this.utils.getStore("readingLog"));
            if (map.has(this.bookId)) {
              this.currentChapterSort = map.get(this.bookId);
            }
          }
        }
      }
    },
    //实际的拦截操作
    doIt() {
      //此处添加500毫秒延迟，目的是等待历史记录变化之后再添加空地址，使空地址能准确添加到栈顶，防止出错
      setTimeout(() => {
        if (!(history.state && history.state.target == "Final")) {
          window.history.pushState(
            { target: "MeanSure", random: Math.random() },
            "",
            location.href
          );
          window.history.pushState(
            { target: "Final", random: Math.random() },
            "",
            location.href
          );
        }
        window.addEventListener(
          "popstate",
          this.goBack,
          //此处可调用一些自定义的操作，例如弹窗提示之类的，最后根据实际需要可调用上面三个函数中的任何一个，用于决定当前自定义操作完成之后，需要停留在本页面，还是回退，还是跳转到其他页面
          //stay();如此操作会停留在本页面
          //back();如此操作会无副作用回退到上一级
          //toUrl（'http://www.baidu.com'）;如此操作会执行完之定义操作之后跳转到百度
          false
        );
      }, 250);
    },
    //退出阅读器事件
    goBack(e) {
      if (e.state && e.state.target == "MeanSure") {
        if (this.isBookself === 0 && this.currentChapterSort > 2) {
          history.forward();
          this.isBookselfPopup = true;
        } else {
          this.back();
        }
      }
    },
    back() {
      let backCount = history.state.target == "Final" ? -3 : -2;
      history.go(backCount);
      // window.removeEventListener("popstate", this.back, false);
    },
    // 添加书架弹窗事件
    async addBookself(state) {
      if (state === "confirm") {
        await this.addBookToBookCase();
        if (this.isBookself === 1) {
          this.back();
        }
      } else if (state === "cancel") {
        this.isBookselfPopup = false;
        this.back();
      }
    },
    // 添加到书架
    async addBookToBookCase() {
      if (this.userInfo) {
        let params = {
          bookId: this.bookId, //书籍id
        };
        let res = await this.$api.reader.addBookToBookCase(params);
        if (res.code === 1) {
          this.isBookself = 1;
          this.isBookselfPopup = false;
          Toast("Successful！");
        } else {
          Toast(res.message ? res.message : "Fail to add");
        }
      } else {
        this.setCurrentPopup({ currentPopup: "login" });
        this.setShowPopup(true);
      }
    },
    // 上传阅读记录
    async getReadSave() {
      try {
        let params = {
          contentId: this.currentChapter.contentId, //章节id
          bookId: this.bookId, //书籍id
        };
        await this.$api.reader.getReadSave(params);
        // if (res.code === 1) {
        //   console.log("阅读记录上传成功");
        // }
      } catch (e) {
        console.log(e);
      }
    },
    // 设置Colour
    setPattern(item, index) {
      this.patternActive = index;
      this.setUserLocalStorage();
    },
    //切换夜间模式
    switchTheme() {
      if (this.patternActive === 3) {
        this.patternActive = 0;
      } else {
        this.patternActive = 3;
      }
      this.setUserLocalStorage();
    },
    // 切换章节
    async toggleChapter(item) {
      await this.sendLog("book_read_analysis");
      this.currentChapterSort = item.sort;
      this.isChapterList = false;
      if (this.userInfo) {
        this.getReadSave();
      }
    },
    // 加减章节
    async preOrNextChapter(str) {
      await this.sendLog("book_read_analysis");
      if (str === "pre") {
        if (this.currentChapterSort <= 1) {
          return;
        } else {
          this.currentChapterSort -= 1;
        }
      } else if (str === "next") {
        if (this.currentChapterSort >= this.chapterList.length) {
          this.$router.push({
            name: "bookEnd",
            params: { bookId: this.bookId },
          });
          return;
        } else {
          this.currentChapterSort += 1;
        }
      }
      if (this.userInfo) {
        this.getReadSave();
      }
    },
    // 解锁章节
    async unlockChapter(toName) {
      if (toName === "premium") {
        // 跳转开通会员页
        this.$router.push({
          name: "premium",
        });
      } else if (toName === "myAccount") {
        // 跳转我的账户页 打开充值浮窗
        await this.getCoinAndVipRecharge();
        this.payPopup = true;
      } else if (toName === "unlock") {
        // 解锁本章节并扣除书币
        this.buyChapter(this.currentChapter.contentId);
      }
    },
    // 查询书币充值和连续充值套餐列表
    async getCoinAndVipRecharge() {
      let res = await this.$api.home.getCoinAndVipRecharge({});
      if (res.code === 1) {
        Object.keys(res.source).forEach((key, idx) => {
          this.cardList[key] = res.source[key].slice(0, 3);
          if (idx === 0) {
            this.currentCard = res.source[key][0];
          }
        });
      }
    },
    //字体设置
    fontSet(str) {
      this.option = true;
      if (str === "reduce") {
        if (this.fontSize === 14) {
          return;
        } else {
          this.fontSize -= 1;
          this.setUserLocalStorage();
        }
      }
      if (str === "add") {
        if (this.fontSize === 22) {
          return;
        } else {
          this.fontSize += 1;
          this.setUserLocalStorage();
        }
      }
    },
    //无限加载
    loadMore() {
      this.loading = true;
      if (this.bookCurrentPage === this.bookSourceLinks.length) {
        return;
      }
      this.moreLoading = true;
      this.bookCurrentPage++;
      setTimeout(() => {
        this.getChapters(this.bookSourceLinks[this.bookCurrentPage]);
        if (this.getBookLocalStorage()[this.bookId]) {
          this.setBookLocalStorage();
        }
        this.loading = false;
        this.moreLoading = false;
      }, 2500);
    },
    //AES解密
    decryptAES(word, keyStr, ivStr) {
      keyStr = keyStr ? keyStr : "youhewenhua!2022";
      ivStr = ivStr ? ivStr : "2022!youhewenhua";
      let key = CryptoJS.enc.Utf8.parse(keyStr);
      let iv = CryptoJS.enc.Utf8.parse(ivStr);
      let encryptedHexStr = CryptoJS.enc.Hex.parse(word);
      let src = CryptoJS.enc.Base64.stringify(encryptedHexStr);
      let decrypt = CryptoJS.AES.decrypt(src, key, {
        iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.ZeroPadding, // Pkcs7
      });
      let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
      return decryptedStr.toString();
    },
    // 返回顶部
    backTop() {
      this.$refs.wrapper.scrollTop = 0;
      let timer = setInterval(() => {
        let ispeed = Math.floor(-this.scrollTop / 5);
        document.documentElement.scrollTop = document.body.scrollTop =
          this.scrollTop + ispeed;
        if (this.scrollTop === 0) {
          clearInterval(timer);
        }
      }, 160);
    },
  },
};
</script>

<style lang="scss" scoped>
.reader {
  > .book {
    width: 100%;
    height: 100vh;
    overflow-x: hidden;
    overflow-y: scroll;
    position: relative;
    // 引导页
    .bootPage {
      width: 100%;
      height: 100%;
      position: fixed;
      top: 0;
      left: 0;
      z-index: 10000;
      background: rgba(50, 51, 52, 0.9);
      display: flex;
      align-items: center;
      justify-content: space-between;
      color: #d0d0d0;
      .b-item {
        padding: 0 20px;
        flex: 1;
        line-height: 100vh;
        &.bootPage-center {
          text-align: center;
          border-left: 1px solid #5c5c5c;
          border-right: 1px solid #5c5c5c;
        }
        &.bootPage-left {
          text-align: left;
        }
        &.bootPage-right {
          text-align: right;
        }
      }
    }
    .books-con {
      width: 100%;
      .book-head {
        &.head-height {
          height: 84px;
        }
        .book-head-Popup {
          width: 100%;
          .mint-header {
            width: 100%;
            height: 84px;
            padding: 0 40px;
            background: #333333;
            font-size: 28px;
            font-family: PingFang-SC-Medium, PingFang-SC;
            ::v-deep .mint-header-button {
              .mintui {
                font-size: 36px;
              }
            }
          }
        }
      }
      .book-content {
        padding: 50px 40px;
        white-space: pre-wrap;
        // margin-top: 84px;
        .book-title {
          line-height: 48px;
          font-size: 34px;
          margin-bottom: 48px;
        }
        .book-inner {
          font-family: PingFangSC-Semibold, PingFang SC;
          font-size: 22px;
          // font-weight: 600;
          text-align: justify;
          line-height: 40px;
        }
      }
    }
  }
  .book-foot {
    width: 100%;
    height: 402px;
    // display: none;
    .add-bookself {
      width: 362px;
      height: 96px;
      font-size: 30px;
      color: #cccccc;
      display: flex;
      justify-content: center;
      align-items: center;
      background: #3b3b3b;
      position: fixed;
      bottom: 426px;
      left: 0;
      right: 0;
      margin: auto;
      border-radius: 48px;
      border: 1px solid #cccccc;
      .svg-icon {
        width: 56px;
        height: 56px;
        margin-right: 8px;
      }
    }
    .page-read-option {
      width: 100%;
      height: 402px;
      padding: 30px;
      box-sizing: border-box;
      font-size: 28px;
      font-weight: bold;
      display: none;
      color: #fff;
      box-shadow: 0px -2px 6px 0px rgba(0, 0, 0, 0.02);
      background: #333333;
      position: fixed;
      bottom: 0;
      left: 0;
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      > ul {
        display: flex;
        flex: 1;
        align-items: center;
        &.set-fontSize {
          &::before {
            content: "Font size";
            width: 156px;
            font-family: PingFang-SC-Bold, PingFang-SC;
          }
          li {
            &.fontSize-reduce,
            &.fontSize-add {
              width: 160px;
              height: 48px;
              text-align: center;
              line-height: 48px;
              color: #fff;
              border-radius: 25px;
              border: 1px solid #fff;
              &.fontSize-astrict {
                color: #969696;
                border-color: #969696;
              }
            }
            &.fontSize-num {
              margin: 0 55px;
              font-weight: 500;
              font-family: PingFangSC-Medium, PingFang SC;
            }
          }
        }
        &.set-colour {
          &::before {
            width: 156px;
            content: "Colour";
            font-family: PingFang-SC-Bold, PingFang-SC;
          }
          li {
            width: 82px;
            height: 34px;
            padding: 5px;
            background-clip: content-box;
            border-radius: 24px;
            &:not(&:last-child) {
              margin-right: 45px;
            }
            &.active {
              border: 1px solid #e86472;
            }
          }
        }
        &.set-list {
          justify-content: space-between;
          li {
            .svg-icon {
              width: 44px;
              height: 44px;
            }
          }
        }
      }
    }
  }
  > .chapter-list {
    .mint-popup {
      width: 565px;
      height: 100%;
      overflow: hidden;
      .chapter-head {
        &::before {
          content: "Catalogue";
          height: 53px;
          text-align: center;
          color: #333333;
          margin-top: 64px;
          display: block;
          font-size: 32px;
          font-weight: 600;
        }
        .chapter-head-box {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 35px 26px 16px 32px;
          border-bottom: 1px solid #eeeeee;
          .episodes {
            font-size: 26px;
            color: #666666;
          }
          .sort {
            .svg-icon {
              width: 56px;
              height: 56px;
            }
          }
        }
      }
      .list {
        width: 565px;
        height: calc(100% - 284px);
        padding: 30px 0;
        overflow-y: auto;
        color: #999999;
        background: #fff;
        li {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 16px 32px;
          font-size: 32px;
          font-weight: 500;
          line-height: 49px;
          font-family: PingFangSC-Medium, PingFang SC;
          &.active {
            color: #e86472;
          }
          &::before {
            content: attr(chapterName-content);
            display: inline-block;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          .lock-box {
            margin-left: 32px;
            .svg-icon {
              height: 30px;
              &.unlock-icon {
                width: 32px;
              }
              &.lock-icon {
                width: 26px;
              }
            }
          }
        }
      }
    }
  }
  > .add-bookself-box {
    .mint-popup {
      background: none;
      .bookself-popup {
        width: 624px;
        height: 416px;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        padding: 0 38px;
        box-sizing: border-box;
        background: #fff;
        border-radius: 32px;
        position: relative;
        .bookself-bg {
          width: 175px;
          height: 175px;
          position: absolute;
          top: -69px;
          left: 0;
          right: 0;
          margin: auto;
        }
        .content {
          text-align: center;
          line-height: 54px;
          font-size: 32px;
          font-weight: 600;
          color: #333333;
          margin-top: 106px;
        }
        .foot-btn {
          display: flex;
          justify-content: space-between;
          .mint-button {
            width: 250px;
            height: 88px;
            font-size: 32px;
            font-weight: 500;
            border-radius: 16px;
            &.cancel {
              color: #999999;
              background: #eeeeee;
            }
            &.confirm {
              color: #ffffff;
              background: linear-gradient(90deg, #ef6a59 0%, #e25177 100%);
            }
          }
        }
      }
    }
  }
  > .unlock-chapter {
    .mint-popup {
      width: 100%;
      background: none;
      .unlock-chapter-popup {
        width: 100%;
        height: 996px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        box-sizing: border-box;
        padding: 24px 0 48px 0;
        background: #fff;
        text-align: center;
        > h3.title {
          font-size: 34px;
          color: #333333;
          line-height: 56px;
          &::after {
            content: "Please support the original author as well as the genuine reading.";
            display: block;
            font-size: 30px;
            font-weight: 400;
            line-height: 49px;
            padding: 0 85px;
            margin-top: 32px;
          }
        }
        > .unlock-btn-box {
          padding: 0 77px;
          margin-top: 50px;
          .mint-button {
            width: 100%;
            height: 100px;
            color: #fff;
            font-size: 34px;
            background: #e86472;
            border-radius: 20px;
            border: 3px solid #e86472;
            &.free-btn {
              display: flex;
              justify-content: center;
              align-items: center;
              margin-bottom: 48px;
              color: #e86472;
              background: #fff;
              .mint-button-icon .svg-icon {
                width: 44px;
                height: 40px;
                margin-right: 21px;
              }
            }
          }
        }
        > .auto-subscribe {
          display: flex;
          justify-content: center;
          align-items: center;
          margin-top: 24px;
          font-size: 34px;
          color: #333333;
          font-weight: 500;
          line-height: 56px;
          > input {
            width: 36px;
            height: 36px;
            margin-right: 10px;
          }
        }
        > .account-balance {
          height: 158px;
          margin-top: 88px;
          font-size: 30px;
          display: flex;
          flex-direction: column;
          justify-content: space-around;
          > p {
            color: #e86472;
            &::before {
              content: "Account balance:";
              color: #999999;
              font-weight: 500;
              margin-right: 8px;
            }
          }
          &.subscribe::after {
            content: attr(subscribe-content);
            min-width: 500px;
            height: 76px;
            padding: 0 32px;
            white-space: nowrap;
            font-weight: 500;
            border-radius: 38px;
            color: #666666;
            line-height: 76px;
            margin: auto;
            display: block;
            border: 2px solid #eeeeee;
          }
        }
        > .foot-btn {
          padding: 31px 0 0 0;
          border-top: 2px dashed #cccccc;
        }
      }
    }
  }
  > .products-pay {
    .mint-popup {
      width: 100%;
      background: none;
      .pay-popup {
        width: 100%;
        height: 1123px;
        background: #fff;
        &::before {
          content: "Product";
          display: block;
          padding: 32px 32px 7px;
          color: #333333;
          font-size: 32px;
          font-weight: 600;
          line-height: 53px;
        }
        .header {
          display: flex;
          align-items: center;
          padding: 0 32px;
          line-height: 26px;
          font-size: 22px;
          font-weight: 500;
          color: #999999;
          white-space: pre-wrap;
          .view-all {
            white-space: nowrap;
            color: #e86472;
            float: right;
          }
        }
        .card-list-box {
          padding: 0 32px;
          > ul.card-list {
            margin-top: 46px;
            display: flex;
            flex-wrap: nowrap;
            > li {
              width: 196px;
              height: 208px;
              font-weight: 500;
              padding-top: 12px;
              display: flex;
              flex-direction: column;
              // justify-content: space-between;
              text-align: center;
              box-sizing: border-box;
              border: 2px solid #eeeeee;
              border-radius: 16px;
              position: relative;
              &:nth-child(2) {
                margin: 0 49px;
              }
              .info {
                margin: auto 10px;
                h3 {
                  font-weight: 500;
                  font-size: 32px;
                  color: #333333;
                  &::after {
                    content: attr(title-content);
                    margin-left: 8px;
                    font-size: 20px;
                  }
                }
                .desc {
                  line-height: 28px;
                  font-size: 22px;
                  color: #e86472;
                  &::before {
                    content: attr(add-content);
                  }
                  &::after {
                    content: attr(desc-content);
                    margin-left: 6px;
                  }
                }
              }
              .price {
                width: 100%;
                height: 56px;
                box-sizing: border-box;
                padding: 0 10px;
                display: flex;
                align-items: center;
                justify-content: center;
                color: #e86472;
                font-size: 32px;
                background: #eeeeee;
                border-radius: 0px 0px 14px 14px;
              }
              &.dot::after {
                content: attr(li-content);
                width: 116px;
                height: 48px;
                box-sizing: border-box;
                display: flex;
                justify-content: center;
                align-items: center;
                position: absolute;
                top: -24px;
                right: 0;
                padding: 0 14px;
                font-size: 20px;
                color: #ffffff;
                font-weight: 500;
                background: #e86472;
                border-radius: 0px 16px 0px 16px;
              }
              &.active {
                border-color: #e86472;
                .price {
                  background: #fceff0;
                }
              }
            }
          }
        }
        .reader-pay-list {
          &::before {
            content: "Payment Method";
            display: block;
            font-size: 32px;
            font-weight: 600;
            color: #333333;
            line-height: 53px;
            margin-left: 32px;
            margin-bottom: 16px;
          }
        }
      }
    }
  }
  > .changeSource {
  }
  .foot-toggle-chapter {
    padding: 40px;
    display: flex;
    justify-content: space-around;
    button {
      min-width: 160px;
      height: 50px;
      padding: 0 15px;
      white-space: nowrap;
      color: #fff;
      border: none;
      font-size: 26px;
      font-weight: bold;
      background: #e86472;
      border-radius: 6px;
      &.toggle-astrict {
        background: #999999;
      }
    }
  }
}
</style>
